package com.snailhd;

import com.snailhd.crawler.DownloadHistoryCsvAndParseToDBExector;
import com.snailhd.dto.QueryStockListDTO;
import com.snailhd.entity.Stock;
import com.snailhd.mapper.StockMapper;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author hd
 * @description
 * @date 2019-10-09 01:06
 */

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SnailhdStockApplications.class)
public class DownloadHistoryCsvAndParseToDBBootstrap {

    @Autowired
    DownloadHistoryCsvAndParseToDBExector exector;

    @Resource
    StockMapper stockMapper;

    @Test
    public void test() throws Exception{

        Long start = System.currentTimeMillis();

        QueryStockListDTO query =QueryStockListDTO.builder().order("code").build();
        List<Stock> list = stockMapper.query(query);

        CountDownLatch countDownLatch = new CountDownLatch(list.size());
        ExecutorService executor = Executors.newFixedThreadPool(4);

        list.forEach(e->{
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        String code = e.getCode();
                        if(e.getSymbol().startsWith("sz")){
                            code = "1"+code;
                        }else if(e.getSymbol().startsWith("sh")){
                            code = "0"+code;
                        }
                        exector.exec(code,false,"19900101","20191103");

                    } catch (Exception ex) {
                        log.error("下载异常{}",e,ex);
                    } finally {
                        countDownLatch.countDown();
                        log.info("------>count:{}",countDownLatch.getCount());
                    }
                }
            });
        });

        countDownLatch.await();
        executor.shutdown();
        Long end = System.currentTimeMillis();
        log.info("----->耗费时间：{}",(double)(end-start)/1000);

    }
}
